<template>
<div class="app-container calendar-list-container">
  <div class="content-container" style="padding-bottom:50px">
              <div style="overflow:hidden">
                  <h3 class="tip">基本信息</h3>
                  <el-col :span="16" style='margin-top:15px;overflow:hidden'>
                    <el-form :label-position="labelPosition" label-width="80px" :model="shopInfo" ref="shopInfo">
                          <div style="overflow: hidden;">
                            <el-form-item label="渠道名称" style="width:48%;float:left">
                              <el-select class="filter-item" v-model="rule.channel" >
                                  <el-option v-for="item in  options" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                              </el-select>
                            </el-form-item> 
                            <el-form-item label="生效时间" label-width="80px" style="width:48%;float:right" class="postInfo-container-item">
                                <el-date-picker v-model="rule.effectTime" type="datetime"  value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
                                </el-date-picker>
                            </el-form-item>  
                          </div>
                          <div style="overflow: hidden;">
                            <el-form-item label="站点选择" style="width:48%;float:left">
                              <el-select class="filter-item" v-model="rule.cityIds" placeholder="请选择省份" @change="change"   >
                                  <el-option v-for="item in  provinceList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                              </el-select>
                            </el-form-item> 
                            <el-form-item label="失效时间" label-width="80px" style="width:48%;float:right" class="postInfo-container-item">
                                <el-date-picker v-model="rule.abateTime" type="datetime"  value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"  placeholder="选择日期时间">
                                </el-date-picker>
                            </el-form-item>   
                          </div>
                          <div style="overflow: hidden;">
                            <el-form-item label="展现位置" style="width:48%;float:left">
                              <el-select class="filter-item" v-model="rule.position" placeholder="请选择省份" @change="change"   >
                                  <el-option v-for="item in  positionOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                              </el-select>
                            </el-form-item> 
                          </div>
                    </el-form>
                </el-col>
              </div>      
              
                <div style="overflow:hidden">
                  <h3 class="tip">内容配置</h3>
                  <el-col :span="16" style='margin-top:15px;overflow:hidden'>
                      <div class="createPost-main-container">
                        <el-form :label-position="labelPosition" label-width="80px" :model="shopInfo" ref="shopInfo">
                                <el-form-item label="标题">
                                    <el-input v-model="rule.title"></el-input>
                                </el-form-item>
                                <el-form-item label="内容描述">
                                  <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 10, maxRows: 40}"
                                    placeholder="请输入内容"
                                    v-model="rule.content">
                                  </el-input>
                                </el-form-item>
                            </el-form>
                          </div>
                      </el-col>
                  </div>
                  <div style="overflow:hidden">
                  <h3 class="tip">图片配置</h3>
                    <div style="padding-bottom:30px">
                      <el-upload class="upload-demo" 
                                  action="https://upload.qbox.me" 
                                  :data="dataObj" 
                                   :show-file-list="false"
                                  :on-preview="handlePreview" 
                                  :on-remove="handleRemove" 
                                  :on-success="onUploadSuccess"
                                  :before-upload="beforeUpload">
                          <el-button size="small" type="primary">点击添加图片</el-button>
                        </el-upload>
                    </div>
                        <div>
                            <el-row style="margin-top:20px" v-for="(rowItem, rowIndex) in splashRows" :key="'row_' + rowIndex">
                              <el-col :span="6" v-for="(o, index) in rowItem" :key="'row_'+rowIndex+'col_' + index" :offset="index > 0 ? 2 : 0">
                                <el-card :body-style="{ padding: '0px' }" style="padding:20px">
                                  <img :src="o.picUrl" class="image">
                                  <div style="padding: 14px;">
                                    <el-input
                                      placeholder="请输入跳转链接"
                                      v-model="o.url"
                                      clearable>
                                    </el-input>
                                    <div class="bottom clearfix">
                                      <el-button type="text" class="button" @click="deleteItemPicClick(rowIndex,index)">删除</el-button>
                                    </div>
                                  </div>
                                </el-card>
                              </el-col>
                            </el-row>
                        </div>
                  </div>
        </div>
        <el-button type="primary"   @click="submit">提交规则</el-button>
    </div>
</template>

<script>
import { searchByKw } from "@/api/user/index";
import { shopList, addOrUpdate } from "@/api/shop/index";
import { mapGetters } from "vuex";
import { getToken } from "@/api/qiniu";
import { itemWithSubLevel, subList } from "@/api/district/index";
import MDinput from "@/components/MDinput";
import { loadRule,ruleAddOrUpdate } from "@/api/rule/index";
import { agentList } from "@/api/agent/index";
const defaultForm = {
  status: "draft",
  title: "", // 文章题目
  content: "", // 文章内容
  content_short: "", // 文章摘要
  source_uri: "", // 文章外链
  image_uri: "", // 文章图片
  source_name: "", // 文章外部作者
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ["a-platform"],
  comment_disabled: false
};

export default {
  components: { MDinput },
  name: "user",
  data() {
    return {
      channel: 1,
      options: [
        {
          name: "客户端",
          id: 1
        },
        {
          name: "商户端",
          id: 0
        }
      ],
      position: 0,
      positionOptions: [
        {
          name: "3秒广告框",
          id: 0
        },
        {
          name: "首页banner",
          id: 1
        }
      ],
      dataObj: { token: "", key: "" },
      fileList2: [
        {
          name: "food.jpeg",
          target: "",
          url:
            "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        },
        {
          name: "food2.jpeg",
          target: "",
          url:
            "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        }
      ],
      postForm: Object.assign({}, defaultForm),
      phoneDisable: false,
      imageUrl: "",
      dataObj: { token: "", key: "" },
      province: "",
      city: "",
      area: "",
      street: "",
      labelPosition: "right",
      formStatus: "create",
      form: {
        username: undefined,
        name: undefined,
        sex: "男",
        password: undefined,
        description: undefined
      },
      rules: {},
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20
      },
      sexOptions: ["男", "女"],
      dialogFormVisible: false,
      dialogStatus: "",
      userManager_btn_edit: true,
      userManager_btn_del: true,
      userManager_btn_add: true,
      textMap: {
        update: "编辑",
        create: "创建"
      },
      tableKey: 0,
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      image: "",
      file: "",
      shopInfo: {
        id: null,
        phone: "",
        name: "",
        provinceId: 355,
        cityId: 356,
        areaId: 357,
        streetId: 358,
        slogan: null,
        description: null,
        shopkeeper: "",
        userId: null,
        longtitude: null,
        latitude: null,
        operateType: 0
      },
      splashs: [],
      splashRows: [],
      rule: {
        id: null,
        channel: 1,
        cityIds: 355,
        position: 0,
        effectTime: "",
        abateTime: "",
        title: "",
        content: "",
        splashs: []
      }
    };
  },
  created() {
    this.postForm = Object.assign({}, defaultForm);
    //加载店铺信息
    if (this.$route.query.id) {
      this.loadRuleMethod(this.$route.query.id);
    }
    this.loadProvince(0);
    this.userManager_btn_edit = true; //this.elements['userManager:btn_edit'];
    this.userManager_btn_del = true; //this.elements['userManager:btn_del'];
    this.userManager_btn_add = true; //this.elements['userManager:btn_add'];
  },
  computed: {
    ...mapGetters(["elements"]),
    contentShortLength() {
      return this.postForm.content_short.length;
    }
  },
  methods: {
    loadRuleMethod(id) {
      loadRule(id).then(resp => {
        this.rule = resp.data;
        this.splashs = this.rule.splashs
        this.splashRows = this.split_array(this.splashs, 3);
      });
    },
    submit() {
      if(!this.rule.abateTime){
        this.$notify({
            title: "提示",
            message: '请设置超期时间',
            type: "warn",
            duration: 2000
          });
        return
      }
      if(!this.rule.effectTime){
        this.$notify({
            title: "提示",
            message: '请设置生效时间',
            type: "warn",
            duration: 2000
          });
        return
      }

      this.rule.splashs = this.splashs;
      ruleAddOrUpdate(this.rule).then(resp => {
        if (resp.status == 200) {
          this.$notify({
            title: "提示",
            message: resp.message,
            type: "success",
            duration: 2000
          });
        }
      });
    },
    deleteItemPicClick(row, col) {
      var realIndex = row * 3 + col;
      this.splashs = this.splashs.filter((itm, idx) => idx != realIndex);
      this.splashRows = this.split_array(this.splashs, 3);
    },
    split_array(arr, len) {
      var a_len = arr.length;
      var result = [];
      for (var i = 0; i < a_len; i += len) {
        result.push(arr.slice(i, i + len));
      }
      return result;
    },
    onUploadSuccess(response, file, fileList) {
      var img = "http://p8x2p1gru.bkt.clouddn.com/" + response.key;
      var item = {
        picUrl: img,
        url: "",
        ruleId: undefined,
        description: ""
      };
      this.splashs.push(item);
      this.splashRows = this.split_array(this.splashs, 3);
    },
    beforeUpload(file) {
      const _self = this;
      return new Promise((resolve, reject) => {
        getToken()
          .then(response => {
            const token = response.data;
            _self._data.dataObj.token = token;
            _self._data.dataObj.key = file.name;
            resolve(true);
          })
          .catch(err => {
            console.log(err);
            reject(false);
          });
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    onShopKeeperChange(val) {
      console.log(val);
      this.phoneDisable = false;
    },
    querySearchAsync(queryString, cb) {
      searchByKw(queryString).then(res => {
        if (res.data) {
          var arrResult = [];
          res.data.forEach(element => {
            var item = {
              value: element.name,
              key: element.phone
            };
            arrResult.push(item);
          });
          cb(arrResult);
        }
      });
    },
    handleSelect(item) {
      console.log(item);
      if (this.shopInfo.shopkeeper != "") {
        this.phoneDisable = true;
      }
      this.shopInfo.phone = item.key;
    },
    loadProvince(id) {
      agentList().then(response =>{
          this.provinceList = response.data;
          console.log(this.provinceList)
        var pro = this.provinceList[0];
        if(!this.$route.query.id){
          this.shopInfo.provinceId = pro.id
          this.rule.cityIds = pro.id
          console.log(this.rule.cityIds)
        }
      })  
    },
    change() {},
    onCancel() {
      this.$router.go(-1);
    },

    handleUpdate(row) {
      getObj(row.id).then(response => {
        this.form = response.data;
        this.dialogFormVisible = true;
        this.dialogStatus = "update";
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(row.id).then(() => {
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          const index = this.list.indexOf(row);
          this.list.splice(index, 1);
        });
      });
    },
    create(formName) {
      //开始时间校验
      console.log(this.shopInfo)



      // var shopParam = {
      //   shop: this.shopInfo
      // };
      // addOrUpdate(shopParam).then(resp => {
      //   this.dialogFormVisible = false;
      //   this.$notify({
      //     title: "成功",
      //     message: "创建成功",
      //     type: "success",
      //     duration: 2000
      //   });
      // });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.content-left {
  float: left;
}
.content-right {
  height: 100px;
  border: 1px solid #ff0000;
  float: left;
  margin-left: 20px;
}

.tip {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border-left: 5px solid #42b983;
  margin: 20px 0;
  color: #757575;
}

.avatar {
  width: 180px;
  height: 180px;
}
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  height: 400px;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>